﻿using System;
using System.Collections.Generic;

namespace SR.ExpressionEvaluator.Lib.Core.Functions
{
    internal class DateDif : IFunction
    {
        List<object> _Args = new List<object>();

        public System.Collections.Generic.List<object> Args
        {
            get
            {
                return _Args;
            }
            set
            {
                _Args = value;
            }
        }

        public object Evaluate()
        {
            if (!Validate())
            {
                throw new Exception("DATEDIF: Validation failed");
            }

            string format = String.Empty;

            if (Args.Count >= 3)
            {
                format = Args[2].ToString();
            }

            DateTime d1 = DateTime.Parse(Args[0].ToString());
            DateTime d2 = DateTime.Parse(Args[1].ToString());

            switch (format.ToLower())
            {
                default:
                case "y":
                    return Math.Abs(d1.Year - d2.Year);

                case "m":
                    return Math.Abs(d1.Month - d2.Month + ((d1.Year - d2.Year) * 12));

                case "d":
                    return Math.Abs((int)(d1 - d2).TotalDays);

                case "ym":
                    return Math.Abs(d1.Month - d2.Month);

                case "yd":
                    // TODO: Implement this
                    throw new NotImplementedException();

                case "md":
                    return Math.Abs(d1.Day - d2.Day);
            }
        }

        public bool Validate()
        {
            if (Args.Count < 2 || Args.Count > 3)
            {
                return false;
            }
            return true;
        }

        public string GetDefinition()
        {
            return @"DATEDIF(<Date 1>,<Date 2>,""y/m/d/ym/yd/md"")";
        }
    }
}
